var BingMap = {};

(function () {
    var map = null, infobox, dataLayer;

    BingMap.GetMap = function (divName, locations, mapOptions) {

        var map = new Microsoft.Maps.Map(document.getElementById(divName), mapOptions);

        dataLayer = new Microsoft.Maps.EntityCollection();
        map.entities.push(dataLayer);

        var infoboxLayer = new Microsoft.Maps.EntityCollection();
        map.entities.push(infoboxLayer);

        infobox = new Microsoft.Maps.Infobox(new Microsoft.Maps.Location(0, 0), { visible: false, offset: new Microsoft.Maps.Point(0, 20) });
        infoboxLayer.push(infobox);

        AddData(locations);
    }

    var AddData = function (locations) {

        var loc;
        var pin;

        for (var i = 0; i < locations.length; i++) {

            loc = new Microsoft.Maps.Location(locations[i].latitude, locations[i].longitude);
            pin = new Microsoft.Maps.Pushpin(loc);

            pin.Title = locations[i].title;
            pin.Description = locations[i].description;
            Microsoft.Maps.Events.addHandler(pin, 'click', displayInfobox);
            dataLayer.push(pin);
        }
    }

    function displayInfobox(e) {
        if (e.targetType == 'pushpin') {
            infobox.setLocation(e.target.getLocation());
            infobox.setOptions({ visible: true, title: e.target.Title, description: e.target.Description });
        }
    }
})();